package threadlocal;


public class ThreadLocalTest {


    public static void main(String[] args) throws InterruptedException {
        //testThreadLocal();
        //tl();
        itl();
    }

    /**
     * ThreadLocal->创建一个变量后，多个线程对其访问都是在访问线程自己的变量
     */
    private static ThreadLocal<String> local = new ThreadLocal<>();

    private static void testThreadLocal() throws InterruptedException {
        local.set("in main");
        System.out.println(local.get());

        new Thread(new Runnable() {
            @Override
            public void run() {
                local.set("in t1");
                System.out.println(local.get());

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        local.set("in t1 t1");
                        System.out.println(local.get());
                    }
                }).start();

                try {
                    Thread.sleep(1000);
                    System.out.println(local.get() + "-in t1 t1");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(local.get());
            }
        }).start();


        System.out.println(local.get());


        new Thread(new Runnable() {
            @Override
            public void run() {
                local.set("in t2");
                System.out.println(local.get());
            }
        }).start();

        Thread.sleep(1000);
        System.out.println(local.get());
    }


    /**
     * 下面两个方法将对比说明如下
     * ①ThreadLocal子线程得不到父线程的值
     * ②InheritableThreadLocal子线程能得到父线程的值
     */
    private static ThreadLocal<String> tl = new ThreadLocal<>();
    private static ThreadLocal<String> itl = new InheritableThreadLocal<>();

    private static void tl() throws InterruptedException {
        tl.set("local1 in father");
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("in thread get father local:" + tl.get());
            }
        }).start();
        System.out.println("in father get father local:" + tl.get());
    }

    private static void itl() throws InterruptedException {
        itl.set("local1 in father");
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("in thread get father local:" + itl.get());
            }
        }).start();
        System.out.println("in father get father local:" + itl.get());
    }
}
